package com.itwk.common.exception;

import com.itwk.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: wangke
 * @Date: 2021/01/11/下午 5:31
 * @Description:
 */

@RestControllerAdvice(basePackages = "com.itwk.gulimall")
public class GuliException {
    //全局异常的valid 校验异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R  ValidException(MethodArgumentNotValidException e){
        Map<String,String> map =new HashMap<>();
        BindingResult bindingResult = e.getBindingResult(); //获取到异常结果
        bindingResult.getFieldErrors().forEach((item->{  //获取遍历异常结果集
            map.put(item.getField(),item.getDefaultMessage());
        }));
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("error", map);
    }

  //捕捉自定义的订单合并异常
    @ExceptionHandler(MergePurchaseException.class)
    public R mergePurchaseException(RuntimeException e){

        return R.error(BizCodeEnume.PURCHASE_EXCEPTION.getCode(),e.getMessage());
    }



       //全局未知异常的处理
    @ExceptionHandler(Exception.class)
    public R UnknowExcepton(Exception e){
       e.printStackTrace();

       return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
